package com.zzyl.framework.datasource.interceptor;

import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.StringContent;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    //解析token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器校验token");
        //获取到token
        String token = request.getHeader("authorization");
        if (!StringUtils.hasText(token)){
            log.info("token为空,拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("解析token");
        try {
            Claims claims = tokenService.parseToken(token);
            Integer userId = (Integer)claims.get("id");
            UserThreadLocal.set(userId.longValue());
        } catch (Exception e) {
           log.error("解析token异常",e);
           return false;
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
